using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Utility;
using PHSRAG.WebControls;
using Utils = PHSRAG.Insight21.InsightUtilities;

namespace PHSRAG.Insight21.COI
{
    public partial class AddDelegates : BasePage
    {
        #region Constants

        /// <summary>Unique string(key) to identify or cache the page index </summary>
        private const string AddDelegatesPageIndexKey = "AddDelegatesPageIndexKey_2A5DAA78-4821-4b71-95A5-62310A03F26F";

        /// <summary>annunciator's general message</summary>
        private const string AnnunciatorTitle = "The following error(s) occurred...";

        /// <summary>Index column in the database</summary>
        private const string PersonIdField = "PersonId";

        #endregion

        #region Instance Variables (Protected)

        //Toggler control
        protected ExpansionToggler expansionToggler;

        #endregion

        #region Instance Variables (Private)

        //cachePolicy
        //Application cache
        private ICachePolicy applicationCachePolicy;
        private ICachePolicy cachePolicy;
        //Id column(Datkey column) for the data source
        private string keyField = "Id";
        private ICachePolicy pageCachePolicy;

        #endregion

        #region property variables

        //parent Id to add users
        private int personId;

        #endregion

        #region Private Properties

        /// <summary> 
        /// Get the COIUserSummary object relevant to the passed in search criteria.
        /// </summary>
        private COIUserSummary COIUserSummary
        {
            get
            {
                COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache;
                CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                if (cOIUserSummary == null)
                {
                    cOIUserSummary = new COIUserSummary(cachePolicy);
                }
                if ((searchContext != null))
                {
                    cOIUserSummary.Load(DataAccess.ConnectionString, searchCriteria, GetPersonId(), (int) Constants.SourcePage.AddDelegatesPage);
                    cOIUserSummary.Cache();
                }

                return cOIUserSummary;
            }
        }

        /// <summary>
        /// Gets/Sets the current page within the datagrid for display. This information persists across page loads.
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.AddDelegatePageKey) as Hashtable;
                return (h == null || h[AddDelegatesPageIndexKey] == null) ? 0 : (int) h[AddDelegatesPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.AddDelegatePageKey) as Hashtable ?? new Hashtable();
                h[AddDelegatesPageIndexKey] = value;
                searchResults.CurrentPageIndex = value;
                pageCachePolicy.Cache(Keys.AddDelegatePageKey, h);
            }
        }

        /// <summary>
        /// Gets the Cached COIUserSummary object
        /// </summary>
        private COIUserSummary GetCOIUserSummaryFromCache
        {
            get { return cachePolicy.GetCachedObject(COIUserSummary.CacheKey) as COIUserSummary; }
        }

        /// <summary>
        /// Gets/Sets the person Id for whom the selected users will be added.
        /// </summary>
        private int GetPersonId()
        {
            try
            {
                Hashtable incomingPageHash =
                    cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingPageHash != null)
                {
                    if (incomingPageHash.ContainsKey(Keys.SupervisorIdKey))
                    {
                        personId = Convert.ToInt32(incomingPageHash[Keys.SupervisorIdKey]);
                    }
                }
                else
                {
                    personId = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId;
                }
            }
            catch (Exception ex)
            {
                ExceptionReport.WriteToEventLog("Error occurred while trying to get the parent Id(AddCOIUsers.GetPersonIds())", ex, true, ExceptionReport.ReportType.Error);
                annunciator.Message = "Error occurred while trying to get the parent Id";
            }
            return personId;
        }

        #endregion

        #region private methods

        /// <summary>
        /// Retrieves the CommonSearchContext from the cache and
        /// performs a User search through the system.
        /// </summary>
        private void PerformSearch()
        {
            CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;
            if (searchContext != null)
            {
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
        }

        /// <summary>
        /// Loads the COIUser details only for those to displayed on the page.
        /// </summary>
        private void LoadDataGrid()
        {
            try
            {
                COIUserSummary cOIUserSummary = COIUserSummary;
                if (cOIUserSummary != null)
                {
                    searchResults.VirtualItemCount = bottomPager.RecordCount =
                        topPager.RecordCount = cOIUserSummary.Count;
                    int currentPageIndex = CurrentPageIndex;
                    int pageCount = (topPager.RecordCount/searchResults.PageSize) +
                        (((topPager.RecordCount%searchResults.PageSize) == 0) ? 0 : 1);
                    bottomPager.PageCount = topPager.PageCount = pageCount;
                    bottomPager.CurrentPage = topPager.CurrentPage = currentPageIndex + 1;

                    DataTable table = cOIUserSummary.GetSummaryList(
                        currentPageIndex*searchResults.PageSize, searchResults.PageSize, DataAccess.ConnectionString, (int) Constants.SourcePage.AddDelegatesPage);
                    searchResults.DataSource = table;
                    searchResults.DataKeyField = keyField;
                    searchResults.DataBind();

                    if (table.Rows.Count == 0)
                    {
                        gridContainer.Visible = false;
                        addtoList.Visible = false;
                        annunciator.Message = "The search criteria yielded no results.";
                    }
                    else
                    {
                        gridContainer.Visible = true;
                        addtoList.Visible = true;
                        annunciator.Message = string.Empty;
                        ManagePagination();
                        ManageNavigationLinks();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionReport.WriteToEventLog("Error occurred while trying to load the search results(Error occured at AddCOIUser.LoadDataGrid())", ex, true, ExceptionReport.ReportType.Error);
                annunciator.Message = "Error occurred while trying to load the search results";
            }
        }

        /// <summary>
        /// Initilize the first record, last record and current page values for the pager controls.
        /// Set the current page index to 0 and manage navigation links.
        /// </summary>
        private void InitializePager()
        {
            bottomPager.FirstRecord = topPager.FirstRecord = 1;
            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(searchResults.PageSize, searchResults.Items.Count);
            bottomPager.CurrentPage = topPager.CurrentPage = 1;
            CurrentPageIndex = 0;
            ManageNavigationLinks();
        }

        /// <summary>
        /// Enables or Disables links to other pages within the grid
        /// </summary>
        private void ManageNavigationLinks()
        {
            bottomPager.EnableFirstPage = topPager.EnableFirstPage =
                bottomPager.EnablePreviousPage = topPager.EnablePreviousPage =
                    (searchResults.CurrentPageIndex != 0);

            bottomPager.EnableLastPage = topPager.EnableLastPage =
                bottomPager.EnableNextPage = topPager.EnableNextPage =
                    (searchResults.CurrentPageIndex != (topPager.PageCount - 1));
        }

        /// <summary>
        /// Pagination management
        /// </summary>
        private void ManagePagination()
        {
            int currentPageIndex = CurrentPageIndex;
            searchResults.CurrentPageIndex = currentPageIndex;

            int startIndex = currentPageIndex*searchResults.PageSize;
            bottomPager.FirstRecord = topPager.FirstRecord = startIndex + 1;

            int lastRecord = COIUserSummary.Count;
            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(startIndex + searchResults.PageSize, lastRecord);
        }


        /// <summary>
        /// Uncaches all objects with data for this page.
        /// </summary>
        private void PurgeCache()
        {
            System.Diagnostics.Trace.WriteLine("Purging AddDelegates Summary...");
            COIUserSummary coiUserSummary = GetCOIUserSummaryFromCache;
            if (coiUserSummary != null)
            {
                coiUserSummary.Purge();
                cachePolicy.UnCache(COIUserSummary.CacheKey);
            }
        }

        /// <summary>
        /// Caches outgoing data with incoming data key for use across pages.
        /// </summary>
        /// <param name="showTargetAsPopUp">set to true, if the target page is to be shown as a popup</param>
        private void CacheOutGoingData(bool showTargetAsPopUp)
        {
            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ShowAsPopUp, showTargetAsPopUp);
            outgoingData.Add(Keys.SupervisorIdKey, GetPersonId());
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
        }

        /// <summary>
        /// This method will perform redirection back to the referring page after clearing the search criteria.
        /// </summary>
        private void CleanCache()
        {
            PurgeCache();
            CacheOutGoingData(true);
            ClearSearchCriteria();
        }

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = AnnunciatorTitle;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        #endregion

        # region Event handlers

        /// <summary>
        /// The page load event handler
        /// </summary>
        /// <param name="sender">Sender,that raised the event</param>
        /// <param name="e">argiments related to the sender</param>	
        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                annunciator.Message = string.Empty;
                annunciator.Title = string.Empty;
                breadCrumb.Add("Add COI Delegates", Settings.GetKeyValue("SubNavigation.CoI.AddUsersURL", string.Empty), Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));

                object isHeaderVisible = Request.QueryString["showHearder"];
                if (isHeaderVisible != null && isHeaderVisible.ToString() == "1")
                {
                    headerSection.Visible = true;
                }

                if (!IsPostBack && postbackGuard.IsValid)
                {
                    searchResults.PageSize = selectedUsers.PageSize = Settings.GetKeyValue("COIDataGrid.ItemsPerPage", 20);
                    CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;

                    gridContainer.Visible = false;
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
            finally
            {
                coiSubNavigation.SelectedLink = "Hierarchy Maintenance";
                coiSubNavigation.AccessLevel = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;
            }
        }

        /// <summary>
        /// Handles events raised by sorting the datagrid.
        /// </summary>
        /// <param name="source">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnSort(object source, DataGridSortCommandEventArgs e)
        {
            try
            {
                if (e.SortExpression != string.Empty)
                {
                    COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache ?? new COIUserSummary(cachePolicy);

                    cOIUserSummary.SortColumn = e.SortExpression;
                    cOIUserSummary.SortAscending = (cOIUserSummary.SortColumn == e.SortExpression) ? !cOIUserSummary.SortAscending : cOIUserSummary.SortAscending;
                    cOIUserSummary.Cache();
                    CurrentPageIndex = 0;
                    LoadDataGrid();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// This event is raised when the page index property is changed on the pager control.
        /// The page's DataGrid is reloaded with the data belonging to page specified by the index.
        /// </summary>
        /// <param name="source">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnPageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            try
            {
                searchResults.CurrentPageIndex = e.NewPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the FirstPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the first page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnFirstPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the LastPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the last page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnLastPage(object sender, CommandEventArgs e)
        {
            try
            {
                int lastPageIndex = topPager.PageCount - 1;
                CurrentPageIndex = lastPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the NextPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the next page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnNextPage(object sender, CommandEventArgs e)
        {
            try
            {
                ++CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Occurs when the PreviousPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the previous page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnPreviousPage(object sender, CommandEventArgs e)
        {
            try
            {
                --CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Handler for event raised while each data grid item is created.
        /// If the item being created is the data grid header, do the following:
        /// Add the appropriate sort symbol to denote ascending/descending sequence for the current sort column.
        /// This requires us to locate the cell which corresponding to the column within the collection of TableCell
        /// maintained by the DataGridItem which is under creation. That collection is indexed numerically, the value being
        /// the position of the column within the columns collection maintained by the data grid.
        /// One simple way to do this is to create static mapping between the name of the column and its index. However, this
        /// suffers from the shortcoming that if the sequence of columns is changed on the page, the static binding MUST
        /// be changed too. If they get out of sync, we would be sorting on inappropriate columns!
        /// To avoid this, and to render the code independent of how the page gets managed, we will build a Hashtable of
        /// column indeces, keyed by the sort expression of each column. That way, we could do a quick lookup to get the
        /// index of a column and set the sort symbol on that column.
        /// If the item being created is a data row item, disable its view state.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache;
                    Label sortSymbol = new Label();
                    sortSymbol.Text = (cOIUserSummary.SortAscending) ? InsightUtilities.Constants.SortAscendingText : InsightUtilities.Constants.SortDescendingText;
                    sortSymbol.Font.Name = InsightUtilities.Constants.SortSymbolFontName;

                    Hashtable columnMap = new Hashtable();
                    foreach (DataGridColumn column in searchResults.Columns)
                    {
                        columnMap[column.SortExpression] = searchResults.Columns.IndexOf(column);
                    }

                    string sortColumn = cOIUserSummary.SortColumn;
                    if (columnMap.ContainsKey(sortColumn))
                    {
                        e.Item.Cells[(int) columnMap[sortColumn]].Controls.Add(sortSymbol);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header breadcrumb navigates.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                PurgeCache();
                coiSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        ///// <summary>
        ///// Purges the cache before the COI subnavigation header performs a redirect.
        ///// </summary>
        ///// <param name="sender">Control which rasied the event.</param>
        ///// <param name="e">Arguments associated with the event.</param>
        //private void OnSubNavigate(object sender, CommandEventArgs e)
        //{
        //    try
        //    {
        //        PurgeCache();
        //    }
        //    catch (Exception ex)
        //    {
        //        DisplayExceptionReport(ex);
        //    }
        //}

        /// <summary>
        /// Event handler for the "AddToList" button click.
        /// Note:Adds the selected users in the search results grid to the selected user grid.
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">arguments of the event</param>
        private void OnAddToList(object sender, ImageClickEventArgs e)
        {
            try
            {
                COIUserSummary cOIUserSummary = GetCOIUserSummaryFromCache;
                DataTable selectedUserTable;
                /* Determine which rows in the grid have been selected, and move them into the 
                 * Selections DataTable */
                if (postbackGuard.IsValid && cOIUserSummary != null)
                {
                    foreach (DataGridItem dgi in searchResults.Items)
                    {
                        CheckBox chkBox = (CheckBox) dgi.Cells[4].Controls[1];
                        if (chkBox != null && chkBox.Checked)
                        {
                            cOIUserSummary.AddSelectedUserToList((int) searchResults.DataKeys[dgi.ItemIndex]);
                        }
                    }
                    cOIUserSummary.Cache();
                    selectedUserTable = cOIUserSummary.GetSelectedUsersSummary(DataAccess.ConnectionString);
                    if (selectedUserTable.Rows.Count > 0)
                    {
                        selectedUsers.DataSource = selectedUserTable;
                        selectedUsers.DataKeyField = keyField;
                        selectedUsers.DataBind();
                        selectedUsersContainer.Visible = true;
                        save.Visible = true;
                    }
                    else
                    {
                        selectedUsersContainer.Visible = false;
                        save.Visible = false;
                    }
                    PerformSearch();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Event handler to add the selected users to the hierarchy
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">arguments of the event</param>
        private void OnSave(object sender, ImageClickEventArgs e)
        {
            try
            {
                ClientScript.RegisterStartupScript(GetType(), "msg", "window.close();window.opener.__doPostBack('ChildWindowPostBack', '');", true);
                Hashtable incomingPageHash =
                    cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingPageHash != null)
                {
                    int parentId = Convert.ToInt32(incomingPageHash[Keys.SupervisorIdKey]);
                    if (selectedUsers.Visible)
                    {
                        DataTable dt = new DataTable();
                        dt.Columns.Add("supervisorId");
                        dt.Columns.Add("delegateId");
                        dt.Columns.Add("removed");

                        foreach (DataGridItem dgi in selectedUsers.Items)
                        {
                            CheckBox chkBox = (CheckBox) dgi.Cells[4].Controls[1];
                            if (chkBox != null && chkBox.Checked)
                            {
                                DataRow dr = dt.NewRow();
                                dr["supervisorId"] = parentId;
                                dr["delegateId"] = (int) selectedUsers.DataKeys[dgi.ItemIndex];
                                dr["removed"] = 0;
                                dt.Rows.Add(dr);
                            }
                        }
                        if (dt.Rows.Count > 0)
                        {
                            DataSet ds = new DataSet();
                            ds.Tables.Add(dt);
                            COIUserSummary.AddDelegateMap(DataAccess.ConnectionString, ds);
                        }
                    }
                }
                CleanCache();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Clears the selection criteria 
        /// </summary>
        private void ClearSearchCriteria()
        {
            CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;

            if (searchContext != null)
            {
                searchContext.Reset(Page.Request.Url.ToString());
            }
        }

        /// <summary>
        /// Even handler for the Cancel button click
        /// Action performed: Redirect back to the referrer page without adding the selected users to the hierarchy.
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">arguments of the event</param>
        private void OnCancel(object sender, ImageClickEventArgs e)
        {
            try
            {
                ClientScript.RegisterStartupScript(GetType(), "msg", "window.close();window.opener.__doPostBack('ChildWindowPostBack', '');", true);
                CleanCache();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Search event handler

        /// <summary>
        /// Handler for the event raised by the CommonSearch control when the "Clear Selection" buttion is clicked upon.
        /// The control clears the criteria (specific to this module).
        /// Since in the page life-cycle, the Load occurs before the Clear event, we have to instigate a re-load of the
        /// data grid to refelect the fact that the search criteria has been cleared.
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnClearSelection(object sender, CommandEventArgs e)
        {
            try
            {
                gridContainer.Visible = false;
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Initiates the search by calling PerformSearch
        /// </summary>
        /// <param name="args">Argument associated with the event (contains the search criteria dictionary)</param>
        protected void OnSearch(SearchCriteriaArgs args)
        {
            try
            {
                PerformSearch();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            applicationCachePolicy = (Policy.ICachePolicy) Application[Policy.Names.ApplicationCachePolicyKey];

            //coiSubNavigation.Navigate += new CommandEventHandler(OnSubNavigate);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.coiAdminSubNavigation.Navigate += new CommandEventHandler(this.OnNavigate);
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.topPager.FirstPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnFirstPage);
            this.topPager.PreviousPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnPreviousPage);
            this.topPager.NextPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnNextPage);
            this.topPager.LastPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnLastPage);
            this.searchResults.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemCreated);
            this.searchResults.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.OnPageIndexChanged);
            this.searchResults.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.OnSort);
            this.bottomPager.FirstPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnFirstPage);
            this.bottomPager.PreviousPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnPreviousPage);
            this.bottomPager.NextPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnNextPage);
            this.bottomPager.LastPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnLastPage);
            this.addtoList.Click += new ImageClickEventHandler(OnAddToList);
            this.cancel.Click += new ImageClickEventHandler(OnCancel);
            this.save.Click += new ImageClickEventHandler(OnSave);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion
    }
}